package com.fjh.springboot_01.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import java.util.*;

@Service
public class AIService {
    @Value("${ai.url}")
    private String aiUrl;

    @Value("${ai.model}")
    private String model;

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public AIService(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    public String generateQuestionContent(String topic, Integer questionType) {
        String prompt = buildQuestionPrompt(topic, questionType);
        return callLocalAI(prompt);
    }

    public String generateStandardAnswer(String questionContent, Integer questionType) {
        String prompt = buildAnswerPrompt(questionContent, questionType);
        return callLocalAI(prompt);
    }

    public List<String> generateOptions(String questionContent, String standardAnswer) {
        String prompt = buildOptionsPrompt(questionContent, standardAnswer);
        String response = callLocalAI(prompt);
        return parseOptions(response);
    }

    private String buildQuestionPrompt(String topic, Integer questionType) {
        String questionTypeStr = getQuestionTypeString(questionType);
        String format = questionType == 2 ? 
            "请根据主题'%s'生成一道%s。要求：\n1. 题目内容中需要包含下划线'_____'表示填空位置\n2. 不要包含任何其他说明或解释" :
            "请根据主题'%s'生成一道%s。要求：\n1. 如果是计算题，必须使用'='表示等号\n2. 不要包含任何其他说明或解释";
        return String.format(format, topic, questionTypeStr);
    }

    private String buildAnswerPrompt(String questionContent, Integer questionType) {
        String format = questionType == 1 ? 
            "请为以下选择题生成答案：\n%s\n要求：只输出一个字母A、B、C或D" :
            "请为以下题目生成答案：\n%s\n要求：\n1. 只输出答案内容\n2. 如果是计算题，必须给出最终结果\n3. 不要包含任何解释、过程或评语";
        return String.format(format, questionContent);
    }

    private String buildOptionsPrompt(String questionContent, String standardAnswer) {
        return String.format(
            "请为以下选择题生成4个选项：\n%s\n正确答案：%s\n要求：\n1. 必须按以下格式输出：\nA. 选项内容\nB. 选项内容\nC. 选项内容\nD. 选项内容\n2. 选项要简洁\n3. 必须包含正确答案",
            questionContent, standardAnswer
        );
    }

    private String getQuestionTypeString(Integer questionType) {
        switch (questionType) {
            case 1: return "选择题";
            case 2: return "填空题";
            case 3: return "简答题";
            case 4: return "综合题";
            default: throw new IllegalArgumentException("未知的题目类型");
        }
    }

    private String callLocalAI(String prompt) {
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            requestBody.put("prompt", prompt);
            requestBody.put("stream", false);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            
            Map<String, Object> response = restTemplate.postForObject(aiUrl, request, Map.class);
            
            if (response != null && response.containsKey("response")) {
                return (String) response.get("response");
            }
            
            throw new RuntimeException("AI 服务响应格式错误");
        } catch (Exception e) {
            throw new RuntimeException("调用 AI 服务失败: " + e.getMessage());
        }
    }

    private List<String> parseOptions(String response) {
        // 解析选项，这里假设返回的是按A、B、C、D格式的文本
        List<String> options = new ArrayList<>();
        String[] lines = response.split("\n");
        for (String line : lines) {
            if (line.matches("^[A-D]\\..+")) {
                options.add(line.substring(2).trim());
            }
        }
        return options.isEmpty() ? Arrays.asList("选项A", "选项B", "选项C", "选项D") : options;
    }
} 